<template>
  <div class="app-container">
    <el-form ref="form" :model="params" :rules="rules" label-width="140px">
      <el-row>
        <el-col :span="6">
          <el-form-item prop="infName" :label="$t('interface.name')">
            <el-input v-model.trim="params.infNameName" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('role.Subordinate')" prop="withGroup">
            <el-select v-model="params.withGroup" clearable="clearable" filterable remote reserve-keyword :placeholder="$t('table.pleaseSelect')">
              <el-option v-for="item in menus" :key="item.id" :label="item.text" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('interface.infNameBiaoshi')" prop="infDescription">
            <el-input v-model.trim="params.infName" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('interface.status')" prop="infDescription">
            <el-select v-model="params.status" clearable="clearable" filterable value-key="id" :placeholder="$t('table.pleaseSelect')">
              <el-option v-for="item in appStatus" :key="item.id" :label="item.text" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-button size="mini" icon="el-icon-plus" type="primary">
          <router-link :to="'/system-set/interface/edit'">{{ $t('btn.add') }}</router-link>
        </el-button>
        <delete-btn v-permission="'gaeaSettingController#deleteById'" :disabled="selectedList.length < 1 || selectedList.length > 1" @handleDelete="handleDelete" />
        <el-button v-permission="'gaeaUserController#resetPassword'" type="warning" icon="el-icon-warning" :disabled="selectedList.length != 1" @click="online">{{ $t('btn.onLine') }}</el-button>
        <el-button v-permission="'gaeaUserController#resetPassword'" type="warning" icon="el-icon-warning" :disabled="selectedList.length != 1" @click="offline">{{ $t('btn.offLine') }}</el-button>
        <el-button v-permission="'gaeaUserController#resetPassword'" type="warning" icon="el-icon-warning" :disabled="selectedList.length != 1" @click="test">{{ $t('interface.audit') }}</el-button>
        <el-col :span="5" style="text-align: center; float: right">
          <el-button type="primary" @click="search('form')">{{ $t('btn.query') }}</el-button>
          <el-button type="danger" @click="reset('form')">{{ $t('btn.reset') }}</el-button>
        </el-col>
      </el-row>
    </el-form>
    <!-- 查询结果列表 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" style="width: 100%" border fit highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column fixed type="selection" width="50" center />
      <el-table-column label="ID" min-width="40" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('interface.name')" min-width="140" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.infNameName }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('interface.infNameBiaoshi')" max-width="120" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.infName }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('interface.SQLsentence')" min-width="130" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.sqlSentence }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('role.Subordinate')" min-width="130" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.withGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('interface.status')" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.statusName }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('businessGlossary.modifyUser')" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.updateBy }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('businessGlossary.modifyTime')" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.operation')" width="160px" align="center">
        <template slot-scope="scope">
          <el-button size="mini" style="margin-right: 2px" type="text">
            <router-link :to="'/system-set/interface/edit?id=' + scope.row.id">{{ $t('table.edit') }}</router-link>
          </el-button>
          <el-button size="mini" style="margin-right: 2px" type="text" @click="power(scope.row)"> {{ $t('table.authorization') }} </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <el-pagination v-show="total > 0" background :current-page.sync="params.pageNumber" :page-sizes="$pageSizeAll" :page-size="params.pageSize" layout="total, prev, pager, next, jumper, sizes" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <!-- 审核弹窗 -->
    <el-dialog :title="$t('btn.test')" width="50%" :close-on-click-modal="false" center :visible.sync="testDialog" @close="closeDialog">
      <el-form ref="userForm" :model="dialogForm" :rules="formRules" label-width="100px">
        <el-row class="form_table">
          <el-col :span="24">
            <el-form-item :label="$t('interface.name')" prop="infName">
              <el-input v-model.trim="dialogForm.infName" :disabled="isDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('interface.SQLsentence')" prop="sqlSentence">
              <el-input v-model.trim="dialogForm.sqlSentence" type="textarea" :disabled="isDisabled" rows="4" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- Container start-->
        <div class="ParyDiv">
          <div class="title" style="border-bottom: 1px dashed #ccc; line-height: 32px; margin-top: 50px">
            <div class="titleStyle">
              <span class="titleStr">
                <span class="spanDiv">
                  <a v-if="isContainerIcon" />
                  <a v-else />
                  {{ $t('interface.requiredParameter') }}
                </span>
              </span>
              <!-- <el-button class="filter-item buttonClass" style="float: right" type="warning" icon="el-icon-plus" @click="addTestData">{{ $t('table.add') }}</el-button> -->
            </div>
          </div>
          <div v-if="isTest">
            <el-table :data="TestData" class="custom-table">
              <el-table-column :label="$t('interface.parameter')">
                <template slot-scope="scope">
                  <div v-if="scope.row.isEdit">
                    <el-input v-model="scope.row.paramName" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column :label="$t('interface.value')">
                <template slot-scope="scope">
                  <div v-if="scope.row.isEdit">
                    <el-input v-model="scope.row.paramDemo" />
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column :label="$t('table.operation')">
                <template slot-scope="scope">
                  <img class="imagedelete" src="../../../assets/images/pick_up.png" @click="deletecontainerData(scope, scope.$index, 'TestData')">
                </template>
              </el-table-column> -->
            </el-table>
          </div>
        </div>
        <!-- 响应结果 -->
        <el-card shadow="hover" class="ms_card">
          <div slot="header" class="clearfix">
            <span style="line-height: 28px">{{ $t('interface.responseResults') }}</span>
            <el-button size="mini" class="fr" type="primary" @click="beautiful">{{ $t('interface.formatting') }}</el-button>
            <el-button type="primary" class="fr" style="margin-right: 8px" @click="textConfirm()">{{ $t('btn.test') }}</el-button>
          </div>
          <el-form-item prop="responseDemo" style="height: 260px" label-width="0">
            <el-input v-model="dialogForm.responseDemo" type="textarea" :rows="12" />
          </el-form-item>
        </el-card>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button type="primary" style="margin-right: 8px" @click="auditConfirm()">{{ $t('interface.audit') }}</el-button>
        <el-button @click="testDialog = false">{{ $t('btn.close') }}</el-button>
      </div>
    </el-dialog>
    <!--弹出框-->
    <el-dialog v-if="dialogPowerVisible" :title="$t('interface.InterfaceApplicationAuthorization')" :visible.sync="dialogPowerVisible" :close-on-click-modal="false" width="850px" center class="power">
      <el-form ref="powerForm" :model="powerForm" label-position="left" label-width="100px">
        <div style="text-align: center">
          <!-- :left-default-checked="[2, 3]"
            :right-default-checked="[1]" -->
          <el-transfer
            v-model="appIds"
            style="text-align: left; display: inline-block"
            filterable
            :titles="[$t('interface.unauthorized'), $t('interface.beAuthorized')]"
            :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}',
            }"
            :props="{
              key: 'id',
              label: 'text',
            }"
            :data="powerData"
            @change="handleChange"
          >
            <span slot-scope="{ option }">{{ option.text }}</span>
          </el-transfer>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPowerVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="submitPower('powerForm')">{{ $t('btn.confirmP') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageList, businessApplication, addApplication, deleteApplication, online, offline, test, authorization, queryPowerFun, submitPowerFun, audit, getRelationListInfApp } from '@/api/generator/interface'
import { getDictList } from '@/api/dict-data'
export default {
  data() {
    return {
      total: 1,
      dialogPowerVisible: false,
      appStatus: [],
      powerForm: {
        respExample: '',
      },
      powerData: [],
      savePowerDate: [],
      appIds: [],
      isDisabled: true,
      appIdStatus: false,
      confirmStatus: false,
      isContainer: false,
      isContainerIcon: false,
      isTest: true,
      containerData: [],
      TestData: [],
      selectedList: [],
      rules: {
        requestUrl: [{ required: false, message: this.$t('placeholder.input'), trigger: 'blur' }],
        pageTitle: [{ required: false, message: this.$t('placeholder.input'), trigger: 'blur' }],
        userName: [{ required: false, message: this.$t('placeholder.input'), trigger: 'blur' }],
      },
      menus: [],
      params: {
        pageNumber: 1,
        pageSize: 10,
        status: '',
        infName: '',
        description: '',
        withGroup: '',
        sort: 'update_time',
        order: 'DESC',
      },
      list: null,
      totalCount: 0,
      authorizedName: '',
      totalPage: 0,
      listLoading: true,
      // 项目基础配置
      basicDialog: false,
      testDialog: false,
      statusMap: {
        0: '编辑中',
        1: '测试通过',
        2: '已上线',
        3: '已下线',
      },
      dailogName: '',
      dialogForm: {
        id: '',
        appId: '',
        appName: '',
        status: '',
        remark: '',
        responseDemo: '',
      },
      formRules: {
        appId: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        appName: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        status: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        remark: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
      },
    }
  },
  created() {
    this.queryByPage()
    this.queryPower()
    getDictList('INF_WITH_GROUP').then(({ data }) => {
      this.menus = data
    })
    getDictList('INF_STATUS').then(({ data }) => {
      this.appStatus = data
    })
  },
  methods: {
    beautiful() {
      this.dialogForm.responseDemo = this.getFormatData(this.dialogForm.responseDemo)
    },
    /**
     * JOSN数据格式化
     * @param  json
     */
    getFormatData(json) {
      // eslint-disable-next-line no-redeclare
      var json = json + ''
      if (json.indexOf('{') == -1 && json.indexOf('[') == -1) {
        return json
      } else {
        return this.formatJson(json)
      }
    },
    formatJson(json) {
      // eslint-disable-next-line one-var
      var i = 0,
        il = 0,
        tab = '    ',
        newJson = '',
        indentLevel = 0,
        inString = false,
        currentChar = null
      for (i = 0, il = json.length; i < il; i += 1) {
        currentChar = json.charAt(i)
        switch (currentChar) {
          case '{':
          case '[':
            if (!inString) {
              newJson += currentChar + '\n' + this.repeat(tab, indentLevel + 1)
              indentLevel += 1
            } else {
              newJson += currentChar
            }
            break
          case '}':
          case ']':
            if (!inString) {
              indentLevel -= 1
              newJson += '\n' + this.repeat(tab, indentLevel) + currentChar
            } else {
              newJson += currentChar
            }
            break
          case ',':
            if (!inString) {
              newJson += ',\n' + this.repeat(tab, indentLevel)
            } else {
              newJson += currentChar
            }
            break
          case ':':
            if (!inString) {
              newJson += ': '
            } else {
              newJson += currentChar
            }
            break
          case ' ':
          case '\n':
          case '\t':
            if (inString) {
              newJson += currentChar
            }
            break
          case '"':
            if (i > 0 && json.charAt(i - 1) !== '\\') {
              inString = !inString
            }
            newJson += currentChar
            break
          default:
            newJson += currentChar
            break
        }
      }
      return newJson
    },
    repeat(s, count) {
      return new Array(count + 1).join(s)
    },
    formatterStatus(row, column) {
      return this.statusMap[row.status]
    },
    async submitPower() {
      console.log(this.appIds)
      // 授权确认
      const powerForm = { appIds: this.appIds.join(',') }
      const { code } = await submitPowerFun(this.authorizedName, powerForm)
      if (code != '200') return
      this.dialogPowerVisible = false
      this.queryByPage()
    },
    power(row) {
      console.log(this.savePowerDate)
      getRelationListInfApp({ infName: row.infName }).then((res) => {
        const authorizedApps = res.data || []
        this.powerData = [...this.savePowerDate]
        this.method = row.method
        this.authorizedName = row.infName
        this.appIds = authorizedApps.map((item) => item.appId)
        this.dialogPowerVisible = true
        // if (row.authorizedApps) {
        //   this.appIds = row.authorizedApps.split(',')
        // } else {

        // }
      })
      // if (row.authorized === 1) {

      // } else {
      //   alert('不需要授权')
      // }
    },
    async queryPower() {
      const res = await queryPowerFun()
      if (res.code != '200') return
      this.savePowerDate = [...res.data]
    },
    handleChange(value, direction, movedKeys) {
      // console.log(value, direction, movedKeys)
    },
    deletecontainerData(row, index, name) {
      this[name].splice(index, 1)
    },
    textConfirm() {
      this.$refs.userForm.validate(async(valid, obj) => {
        if (valid) {
          const TestDataPar = {}
          this.TestData.map((item, index) => {
            const itemKey = item.paramName
            TestDataPar[itemKey] = item.paramDemo
          })
          // const TestDataCopy = JSON.stringify(TestDataPar)
          this.dialogForm.queryParams = TestDataPar
          const res = await test(this.dialogForm)
          if (res.code != '200') return
          this.dialogForm.responseDemo = JSON.stringify(res.data)
        } else {
          return
        }
      })
    },
    addTestData() {
      // 新增一条空表单
      this.TestData.push({
        paramName: null,
        paramDemo: null,
        isEdit: true,
      })
    },
    addContainerData() {
      // 新增一条空表单
      this.containerData.push({
        paramName: null,
        description: null,
        dataType: null,
        paramDemo: null,
        sort: null,
        checkRule: null,
        isEdit: true,
      })
    },
    ContainerFunction() {
      // Container查询
      this.isContainer = !this.isContainer
      this.isContainerIcon = !this.isContainerIcon
      this.containerDatasigns++
    },
    async auditConfirm() {
      // 审核
      const { code } = await audit(this.dialogForm.id)
      // const { code } = await deleteUser(this.selectedList[0].id) // 暂时保留单删接口
      if (code != '200') return
      this.testDialog = false
      this.queryByPage()
    },
    // 测试
    async test() {
      // 需要弹窗
      this.testDialog = true
      this.isDisabled = true
      this.dialogForm.id = this.selectedList[0].id
      this.dialogForm.infName = this.selectedList[0].infName
      this.dialogForm.sqlSentence = this.selectedList[0].sqlSentence
      this.TestData = JSON.parse(this.selectedList[0].requestParams)
    },
    // 下线
    async offline() {
      this.$confirm(this.$t('interface.offlineMessage'), this.$t('promptMessage.deleteTipTitle'), {
        confirmButtonText: this.$t('btn.confirmP'),
        cancelButtonText: this.$t('table.cancel'),
        type: 'warning',
      })
        .then(() => {
          this.offlineFun()
        })
        .catch(() => {})
    },
    async offlineFun() {
      const ids = this.selectedList.map((item) => item.id)
      const { code } = await offline(ids)
      // const { code } = await deleteUser(this.selectedList[0].id) // 暂时保留单删接口
      if (code != '200') return
      this.queryByPage()
    },
    // 上线
    async online() {
      this.$confirm(this.$t('interface.onlineMessage'), this.$t('promptMessage.deleteTipTitle'), {
        confirmButtonText: this.$t('btn.confirmP'),
        cancelButtonText: this.$t('table.cancel'),
        type: 'warning',
      })
        .then(() => {
          this.onLineFun()
        })
        .catch(() => {})
    },
    async onLineFun() {
      const ids = this.selectedList.map((item) => item.id)
      const { code } = await online(ids)
      // const { code } = await deleteUser(this.selectedList[0].id) // 暂时保留单删接口
      if (code != '200') return
      this.queryByPage()
    },
    // 选择项改变时
    handleSelectionChange(val) {
      this.selectedList = val
    },
    // 删除操作
    async handleDelete() {
      const ids = this.selectedList.map((item) => item.id)
      const { code } = await deleteApplication(ids)
      // const { code } = await deleteUser(this.selectedList[0].id) // 暂时保留单删接口
      if (code != '200') return
      this.queryByPage()
    },
    // 查询
    search(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('submit!')
          this.params.pageNumber = 1
          this.queryByPage()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重置
    reset(formName) {
      this.$refs[formName].resetFields()
      this.params.userName = ''
      this.params.pageTitle = ''
      this.params.requestUrl = ''
      this.queryByPage()
    },
    async queryByPage() {
      const res = await pageList(this.params)
      if (res.code != '200') return
      this.listLoading = true
      this.list = res.data.records
      this.total = res.data.total
      // this.totalPage = res.data.pages
      this.listLoading = false
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.queryByPage()
    },
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.queryByPage()
    },
    // 关闭模态框
    closeDialog(bool) {
      bool && this.search('form') // 点确定关闭弹窗的时候才会刷新列表
      this.$refs['userForm'].resetFields()
      this.basicDialog = false
    },
    // 新增按钮
    confirmAdd() {
      this.$refs.userForm.validate(async(valid, obj) => {
        if (valid) {
          this.dialogForm.paramDTOD = this.containerData
          const { code } = await addApplication(this.dialogForm)
          if (code != '200') return
          this.closeDialog(true)
        } else {
          return
        }
      })
    },
    // 提交按钮
    confirm() {
      this.$refs.userForm.validate(async(valid, obj) => {
        if (valid) {
          const { code } = await businessApplication(this.dialogForm)
          if (code != '200') return
          this.closeDialog(true)
        } else {
          return
        }
      })
    },
  },
}
</script>
<style scoped lang="scss">
.header {
  line-height: 40px;
  font-weight: bold;
  text-indent: 3rem;
  background: #f9fcff;
  margin-bottom: 5px;
}
.imagedelete {
  width: 15px;
  margin-top: 6px;
}
</style>
